package com.enjoyor.soa.traffic.frame.support.service;

import org.apache.commons.lang3.StringUtils;

import com.enjoyor.filter.SSOClientfilter;
import com.enjoyor.soa.traffic.frame.constant.AuthConstant;
import com.enjoyor.soa.traffic.frame.security.bean.dto.UserDto;
import com.enjoyor.soa.traffic.util.helper.JsonHelper;

public abstract class BaseService {

    public boolean checkToken(String token) {
        UserDto currentUser = this.getCurrentUser(token);
        if (currentUser != null)
            return true;
        return false;
    }

    public String getUserNameByToken(String token) {
        UserDto currentUser = this.getCurrentUser(token);
        if (currentUser != null)
            return currentUser.getSsoUserName();
        else
            return AuthConstant.UNKNOWN_USER;
    }

    public String getPersonNameByToken(String token) {
        UserDto currentUser = this.getCurrentUser(token);
        if (currentUser != null)
            return currentUser.getPersonName();
        else
            return AuthConstant.UNKNOWN_USER;
    }

    public String getUserDeptByToken(String token) {
        UserDto currentUser = this.getCurrentUser(token);
        if (currentUser != null) {
            if (currentUser.getDataAccessRights() != null && !currentUser.getDataAccessRights().isEmpty())
                return currentUser.getDataAccessRights().get(0).getOrgId();
            else
                return currentUser.getOrgId();
        }
        return AuthConstant.UNKNOWN_USER;
    }

    private UserDto getCurrentUser(String token) {
        String authorizeStr =  JsonHelper.beanToJsonStr(SSOClientfilter.getUserInfo(token));;
        if (authorizeStr != null && !StringUtils.isBlank(authorizeStr)) {
            UserDto currentUser = (UserDto) JsonHelper.jsonToObject(authorizeStr, UserDto.class);
            return currentUser;
        }
        return null;
    }

}
